package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.model.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/remove-from-cart")
public class RemoveFromCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        if (id != null) {
            List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart");
            if (cart != null) {
                for (CartItem item : cart) {
                    if (item.getProduct().getProduct_id() == Integer.parseInt(id)) {
                        cart.remove(cart.indexOf(item));
                        break;
                    }
                }
            }
        }
        response.sendRedirect("cart.jsp");
    }

}
